package com.example.demoexcel.service;

import com.alibaba.excel.EasyExcel;
import com.example.demoexcel.model.Person;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 赵恒
 * @date 2023/6/23
 */
@Service
public class PersonService {

    private String dir = "D:\\temp\\easyexcel\\";

    /**
     * 指定包含或排除指定的字段
     */
    public void excludeOrIncludeWrite() {
        List<Person> personList = createPersonList();
        String fileName = dir  + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx";

        // 根据用户传入字段 假设我们要忽略 date
        Set<String> excludeColumnFiledNames = new HashSet<String>();
        excludeColumnFiledNames.add("date");
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(fileName, Person.class).excludeColumnFiledNames(excludeColumnFiledNames).sheet("模板")
                .doWrite(personList);

//        fileName = dir + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx";
//        // 根据用户传入字段 假设我们只要导出 date
//        Set<String> includeColumnFiledNames = new HashSet<String>();
//        includeColumnFiledNames.add("date");
//        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
//        EasyExcel.write(fileName, Person.class).includeColumnFiledNames(includeColumnFiledNames).sheet("模板")
//                .doWrite(personList);
    }

    @SneakyThrows
    public void download(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Person.class).sheet("模板").doWrite(createPersonList());
    }


    public List<Person> createPersonList() {
        List<Person> personList = new ArrayList<>();
        Person person1 = new Person(1, "张三", new Date(), LocalDateTime.now());
        Person person2 = new Person(2, "李四", new Date(), LocalDateTime.now());
        Person person3 = new Person(3, "王五", new Date(), LocalDateTime.now());
        Person person4 = new Person(4, "赵六", new Date(), LocalDateTime.now());

        personList.add(person1);
        personList.add(person2);
        personList.add(person3);
        personList.add(person4);
        return personList;
    }
}
